package net.wwang.blog.controller.user;

import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import net.wwang.blog.pojo.User;
import net.wwang.blog.commons.global.ResponseResult;
import net.wwang.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangWei
 * @date 2020/8/14
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = {"用户接口"})
public class UserApi {
    @Autowired
    private UserService userService;

    /**
     * 初始化管理员账户
     * @param user
     * @param request
     * @return
     */
    @ApiOperation(value = "初始化管理员账户")
    @PostMapping("/admin_account")
    public ResponseResult initManagerAccount(@ApiParam(value = "请求参数：{\"email\":\"\",\"password\":\"\",\"username\":\"\"}" ,required = true) @RequestBody User user, HttpServletRequest request) {
        return userService.initManagerAccount(user,request);
    }

    /**
     * 用户注册
     * @param request
     * @param user
     * @param verifyCode
     * @param captchaCode
     * @param captchaKey
     * @return
     */
    @ApiOperation(value = "注册")
    @PostMapping(value = "/register")
    public  ResponseResult regiser(HttpServletRequest request,
                                   @ApiParam(value = "请求参数：{\"email\":\"\",\"password\":\"\",\"username\":\"\"}" ,required = true)
                                   @RequestBody User user ,
                                   @RequestParam("verifyCode")String verifyCode,
                                   @RequestParam("captcha")String captchaCode,
                                   @RequestParam("captcha_key")String captchaKey){

        return  userService.register(request,user,verifyCode,captchaCode,captchaKey);
    }

    /**
     * 用户登录
     * @param captcha
     * @param captchaKey
     * @param user
     * @param response
     * @param request
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "/login/{captcha}/{captcha_key}")
    public ResponseResult login(@PathVariable("captcha") String captcha,@PathVariable("captcha_key")String captchaKey, @ApiParam(value = "请求参数：{\"password\":\"\",\"username\":\"\"}" ,required = true)@RequestBody User user,HttpServletResponse response,HttpServletRequest request){
        return userService.login(captcha,captchaKey,user,request,response);
    }

    /**
     * 获取验证码
     * @param response
     * @param captchaKey
     */
    @GetMapping("/captcha")
    public void captcha( HttpServletResponse response,@RequestParam("captcha_key")String captchaKey){
       try{
           userService.createCaptcha(response,captchaKey);
       }catch (Exception e){
           e.printStackTrace();
       }
    }


    /**
     * 发送邮箱验证码
     * @param request
     * @param type
     * @param emailAdress
     * @return
     */
    @GetMapping("/varify_code")
    public ResponseResult sendVarifyCode(HttpServletRequest request,@ApiParam(value = "类型：register, forget, update",required = true)@RequestParam("type")String type, @RequestParam("email") String emailAdress){
        return userService.sendEmail(request,emailAdress,type);
    }

    /**
     * 修改用户密码（邮箱验证）
     * @param verifyCode
     * @param user
     * @return
     */
    @PutMapping(value = "/password/{verifyCode}")
    public ResponseResult updatePassword(@PathVariable("verifyCode") String verifyCode,@RequestBody User user){
        return  userService.updateUserPassword(verifyCode,user);
    }

    /**
     * 用户账号详情信息
     * @param userId
     * @return
     */
    @GetMapping(value = "/user_info/{userId}")
    public ResponseResult getUserInfo(@PathVariable("userId") String userId){
        return  userService.getUserInfo(userId);
    }

    /**
     * 修改用户信息
     * @param request
     * @param response
     * @param userId
     * @param user
     * @return
     */
    @PutMapping(value = "/user_info/{userId}")
    public ResponseResult updateUserInfo(HttpServletRequest request,HttpServletResponse response,@PathVariable("userId")String userId,@RequestBody User user){
        return  userService.updateUserInfo(request,response,userId,user);
    }

    /**
     * 获取用户列表（需要管理员权限）
     * @param page
     * @param size
     * @param request
     * @param response
     * @return
     */
    @PreAuthorize("@permission.isRoleAdmin()")
    @GetMapping(value = "/list")
    public ResponseResult getUserList(@RequestParam("page")int page,@RequestParam("size")int size,HttpServletRequest request, HttpServletResponse response){
        return userService.getUserList(page,size,request,response);
    }


    /**
     * 删除用户（管理员操作）
     * @param request
     * @param response
     * @param userId
     * @return
     */
    @PreAuthorize("@permission.isRoleAdmin()")
    @DeleteMapping(value = "/{userId}")
    public ResponseResult deleteUser(HttpServletRequest request,HttpServletResponse response,@PathVariable("userId")String userId){
        return userService.deleteUser(request,response,userId);
    }

    /**
     * 检查Email是否已经注册 SUCCESS：已注册 FAILED ：未注册
     * @param email
     * @return
     */
    @ApiResponses({
            @ApiResponse(code = 200, message = "邮箱已经注册"),
            @ApiResponse(code = 400, message = "邮箱未注册")
    }
    )
    @GetMapping("/eamil")
    public ResponseResult checkEmail(@RequestParam("email") String email){
        return userService.checkEmail(email);
    }

    /**
     * 检查用户名是否已注册 SUCCESS：已注册 FAILED ：未注册
     * @param username
     * @return
     */
    @ApiResponses({
            @ApiResponse(code = 200, message = "用户名已经注册"),
            @ApiResponse(code = 400, message = "用户名未注册")
    }
    )
    @GetMapping("/username")
    public ResponseResult checkUsername(@RequestParam("username") String username){
        return userService.checkUsername(username);
    }


    @PutMapping("/eamil")
    public ResponseResult updateEmail(@RequestParam("verifyCode")String verifyCode,@RequestParam("email")String email,HttpServletRequest request, HttpServletResponse response){
        return userService.updateEmailAdress(verifyCode,email,request,response);
    }

    @GetMapping("/logout")
    public ResponseResult logout(){
        return userService.logout();
    }
}
